package com.iplant.wms.controller.asn;

import com.iplant.base.po.ServiceResult;
import com.iplant.base.po.excel.ExcelData;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.excel.ExcelReader;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.basic.controller.BasicController;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.wms.service.ASNService;
import com.iplant.wms.service.po.asn.WMSArrivalNotice;
import com.iplant.wms.service.po.asn.imp.WMSArrivalNoticeItemImpo;
import com.iplant.wms.service.po.wpo.WMSPurchaseOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购订单
 *
 * @author YouWang·Peng
 * @CreateTime 2022-4-5 11:43:51
 */
@Slf4j
@RestController
@RequestMapping("/api/WMSArrivalNotice")
public class WMSArrivalNoticeController extends BasicController<WMSArrivalNotice> {
    @Autowired
    ASNService wASNService;

    public WMSArrivalNoticeController() {
        super(WMSArrivalNotice.class);
    }

    @PostMapping("/DeleteList")
    public Object DeleteList(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();

        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (!wParam.containsKey("data")) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            // 获取参数
            List<WMSArrivalNotice> wList = CloneTool.CloneArray(wParam.get("data"), WMSArrivalNotice.class);
            if (wList != null) {
                wList.removeIf(p -> p.ID <= 0);
            }
            if (wList == null || wList.size() == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = wASNService.WMS_DeleteArrivalNoticeList(wLoginUser, wList);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }

        return wResult;
    }

    @PostMapping("/Delete")
    public Object Delete(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();

        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (!wParam.containsKey("data")) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            // 获取参数
            WMSArrivalNotice wItem = CloneTool.Clone(wParam.get("data"), WMSArrivalNotice.class);

            if (wItem == null || wItem.ID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = wASNService.WMS_DeleteArrivalNotice(wLoginUser, wItem);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }

        return wResult;
    }

    /**
     * 导入采购订单
     */
    @PostMapping("/Import")
    public Object Import(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (files.length == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "提示：没有要上传的Excel文件！");
            }

            ServiceResult<Integer> wServiceResult = new ServiceResult<Integer>();
            ServiceResult<ExcelData> wExcelData = null;
            String wOriginalFileName = null;
            for (MultipartFile wMultipartFile : files) {
                wOriginalFileName = wMultipartFile.getOriginalFilename();

                if (wOriginalFileName.contains("xlsx")) {
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xlsx", 1000000);
                } else if (wOriginalFileName.contains("xls")) {
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xls", 1000000);
                }

                if (StringUtils.isNotEmpty(wExcelData.FaultCode)) {
                    wResult = GetResult(RetCode.SERVER_CODE_ERR, wExcelData.FaultCode);
                    return wResult;
                }

                wServiceResult = wASNService.WMS_ImportArrivalNotice(wLoginUser, wExcelData.Result);

                if (!StringUtils.isEmpty(wServiceResult.FaultCode)) {
                    break;
                }
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "导入成功!", null, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 用到货单生成收货单及子项
     *
     * @param request
     * @param wParam
     * @return
     */
    @PostMapping("/Create")
    public Object Create(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();

        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (!wParam.containsKey("data")) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            // 获取参数
            WMSPurchaseOrder wWMSPurchaseOrder = CloneTool.Clone(wParam.get("data"), WMSPurchaseOrder.class);
            if (wWMSPurchaseOrder == null || wWMSPurchaseOrder.ID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<WMSArrivalNotice> wServiceResult = wASNService.WMS_CreateArrivalNotice(wLoginUser,
                    wWMSPurchaseOrder);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            log.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }

        return wResult;
    }

    /**
     * 导入到货通知单（和荣版，包含明细）
     */
    @PostMapping("/ImportItems")
    public Object ImportItems(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            if (files.length == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "提示：没有要上传的Excel文件！");
            }

            ServiceResult<List<WMSArrivalNoticeItemImpo>> wServiceResult = new ServiceResult<>();
            ServiceResult<ExcelData> wExcelData = null;
            String wOriginalFileName = null;
            for (MultipartFile wMultipartFile : files) {
                wOriginalFileName = wMultipartFile.getOriginalFilename();

                assert wOriginalFileName != null;
                if (wOriginalFileName.contains("xlsx"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xlsx", 1000000);
                else if (wOriginalFileName.contains("xls"))
                    wExcelData = ExcelReader.getInstance().readMultiSheetExcel(wMultipartFile.getInputStream(),
                            wOriginalFileName, "xls", 1000000);

                assert wExcelData != null;
                if (StringUtils.isNotEmpty(wExcelData.FaultCode)) {
                    wResult = GetResult(RetCode.SERVER_CODE_ERR, wExcelData.FaultCode);
                    return wResult;
                }

                wServiceResult = wASNService.ASN_ImportArrivalNoticeItems(wLoginUser, wExcelData.Result);

                if (!StringUtils.isEmpty(wServiceResult.FaultCode))
                    break;
            }

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "导入成功!", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            log.error("ImportItems", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }
}
